﻿using UnityEngine;

namespace Core
{
    /// <summary>
    /// 序列帧动画组件
    /// </summary>
    public class Sprite4DirAnimationComponent : Component, IAwake, IFrameUpdate
    {
        protected SpriteRenderer renderer;
        protected Anim4DirData animConf;

        protected int currFrame;
        protected int startFrame;

        protected virtual EDir4 GetDir() => EDir4.Down;

        public virtual void Awake()
        {
        }

        public void Tick()
        {
            var index = SysTime.FrameCount - startFrame;
            if (currFrame == index)
            {
                return;
            }
            SetFrame(index);
        }

        public virtual void Play(string res_path)
        {
            animConf = null;
            startFrame = SysTime.FrameCount;

            Load(res_path).Coroutine();

            SetFrame(0);
        }

        protected virtual void SetFrame(int frame)
        {
            currFrame = frame;

            if (renderer == null || animConf == null)
            {
                return;
            }

            EDir4 dir = GetDir();

            var item = animConf.GetAnim(dir);
            var len = item.Sprites.Length;
            if (len == 0)
            {
                return;
            }

            frame = Mathf.Min(currFrame, len - 1);

            renderer.sprite = item.Sprites[frame];
        }

        private async ETVoid Load(string res_path)
        {
            var asset = await G.Res.LoadAsync(res_path);
            animConf = asset?.Obj as Anim4DirData;
            if (animConf == null)
            {
                log.err($"Player动画资源不存在 anim_res={res_path}");
                return;
            }
        }

        //private async ETVoid Play(string anim_res)
        //{
        //    var asset = await G.res.LoadAsync(anim_res);

        //    if (asset == null)
        //    {
        //        Debug.LogError($"Player动画资源不存在 anim_res={anim_res}");
        //        return;
        //    }

        //    var clip = asset.Obj as AnimationClip;

        //    Play(clip, anim_res);
        //}

        //protected void Play(AnimationClip clip, string anim_path)
        //{
        //    //Debug.LogError($"{Time.frameCount} AnimComponent.Play anim={anim_path} ");
        //    if (m_anim_ctl == null)
        //    {
        //        m_cache_anim_path = anim_path;
        //        return;
        //    }
        //    var anim_frame = S.frame.anim;
        //    var delta_time = (anim_frame.frameCount - frameCount) * anim_frame.frameTime;
        //    m_anim_ctl.Play(anim_path, clip.name, clip, false, 0, true, delta_time);
        //}
    }
}
